package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService iRoleService;

    @Autowired
    private IPermissionService iPermissionService;

    @RequestMapping("/list")
    @RequiredPermission(name = "角色查询",expression = "/list")
   public String getList(QueryObject queryObject, Model model){
        PageInfo<Role> que = iRoleService.que(queryObject);
        model.addAttribute("pageInfo",que);
        return "role/list";
    }

    @RequestMapping("/input")
    public String input(Long id,Model model){

        model.addAttribute("p",iPermissionService.selectAll());

        if (id!=null){
            model.addAttribute("role",iRoleService.selectByPrimaryKey(id));
//            根据ID查询当前角色所拥有的的权限
            model.addAttribute("selfPermissions",iPermissionService.selectByRoleId(id));
        }
        return "/role/input";
    }

    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Role role,Long[] ids){

        if (role.getId()!=null){
            iRoleService.updateByPrimaryKey(role);
        }else {
            iRoleService.insert(role);
        }

        for (Long id:ids){
            iRoleService.insertById(role.getId(),id);
        }
        return "redirect:/role/list";
    }


    @RequestMapping("/delete")
    public String delete(Long id){
        if (id!=null){
            iRoleService.deleteByPrimaryKey(id);
            iRoleService.deleteByRoleid(id);
        }
        return "redirect:/role/list";
    }
}
